package com.lihepeng.leecode.linkedList;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个排序链表，删除所有重复的元素，使得每个元素只出现一次。
 * <p>
 * 示例 1:
 * <p>
 * 输入: 1->1->2
 * 输出: 1->2
 */
public class Solution83 {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current = head;
        while (current != null && current.next != null) {
            if (current.value == current.next.value) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
        return head;
    }

    public ListNode deleteDuplicates1(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null) {
            if (fast.value == slow.value) {
                slow.next = fast;
                slow = slow.next;
            }
            fast = fast.next;
        }
        slow.next = null;

        return head;
    }

    /**
     * 2021年3月26日14:15:15
     * 每日一题
     * @param head
     * @return
     */
    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode cur = head;
        while(cur!=null){
            if (cur.value == cur.next.value){
                cur.next = cur.next.next;
            }else {
                cur =cur.next;
            }
        }
        return head;
    }
    private void printList(ListNode listNode){
        List<ListNode> lists = new ArrayList<>();

        while(listNode !=null){
            lists.add(listNode);
            listNode = listNode.next;
        }
        System.out.println(lists);
    }

    /**
     * 2022年3月24日
     * 算法思维训练 使用快慢指针算法
     * @param head
     * @return
     */
    public ListNode deleteDuplicates3(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast!=null) {
            if (fast.value!=slow.value) {
                slow.next = fast;
                slow = slow.next;
            }
            fast = fast.next;
        }
        slow.next =null;
        return head;

    }

    @Test
    public void runTest() {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(1);
        ListNode n3 = new ListNode(2);
        ListNode n4 = new ListNode(3);
        ListNode n5 = new ListNode(3);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        ListNode listNode = deleteDuplicates2(n1);
        System.out.println(listNode);
    }
}
